package com.xps.purifierapp.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.xps.face.util.ConvertUtils;
import com.xps.purifierapp.R;
import com.xps.purifierapp.bean.AZBean;
import com.xps.purifierapp.bean.NotInstalledIBean;
import com.xps.purifierapp.date.net.UserNetWorks;
import com.xps.purifierapp.serciver.UserService;
import com.xps.purifierapp.serciver.UserServiceImpl;
import com.xps.purifierapp.utils.AppCommond;
import com.xps.purifierapp.utils.DensityUtil;
import com.xps.purifierapp.view.wigdet.LoadingDialog;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

public class InstallationdetailsActivity extends AppCompatActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @Bind(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @Bind(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    NotInstalledIBean.ReturnBodyBean returnBodyBean;
    @Bind(R.id.TextView_CardNumber)
    TextView TextViewCardNumber;
    @Bind(R.id.TextView_Commodity)
    TextView TextViewCommodity;
    @Bind(R.id.TextVeiw_OrderPerson)
    TextView TextVeiwOrderPerson;
    @Bind(R.id.TextVeiw_OneContacts)
    TextView TextVeiwTweContacts;
    @Bind(R.id.TextView_Address)
    TextView TextViewAddress;
    @Bind(R.id.TextVeiw_Remarks)
    EditText TextVeiwRemarks;
    @Bind(R.id.btn_anzhuang)
    Button btn_anzhuang;
    @Bind(R.id.tv_feiyong)
    TextView feiyong;
    LoadingDialog loadingDialog;
    @Bind(R.id.TextVeiw_Artificial)
    TextView TextVeiwArtificial;
    @Bind(R.id.TextView_Element)
    TextView TextViewElement;
    @Bind(R.id.TextVeiw_Term)
    TextView TextVeiwTerm;
    @Bind(R.id.Check_Cost)
    CheckBox CheckCost;
    @Bind(R.id.Linear_Cost)
    AutoLinearLayout LinearCost;
    @Bind(R.id.TextView_Total)
    TextView TextViewTotal;
    String Str_Cost;
    String Str_Cost_He;
    int Int_Cost = 0;
    String isCheck = "0";
    @Bind(R.id.btn_return)
    Button btnReturn;
    @Bind(R.id.btn_finish)
    Button btnFinish;
    @Bind(R.id.Image_Install)
    ImageView ImageInstall;
    @Bind(R.id.Image_Scene)
    ImageView ImageScene;
    private android.support.v7.app.AlertDialog alertDialog1;
    private static final int FLAGE_LOAD_IMAGE = 1;
    public static String pathName;
    private UserService userService = new UserServiceImpl();
    String Str_option = "Image_Install";
    String Str_Install = "";
    String Str_Scene = "";
    Dialog bottomDialog;
    ViewGroup.MarginLayoutParams params;
    TextView XiCe_pickPhoto;
    TextView XiJi_takePhoto;
    TextView cancel_TextView;
    private TakePhoto takePhoto;
    private CropOptions cropOptions;
    private InvokeParam invokeParam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_installationdetails);
        ButterKnife.bind(this);
        Intent i = getIntent();
        actionbarTvTitle.setText("安装详情");
        returnBodyBean = (NotInstalledIBean.ReturnBodyBean) i.getSerializableExtra("dataBean");
        TextViewCardNumber.setText(returnBodyBean.getActivation_code());
        TextViewCommodity.setText(returnBodyBean.getProduct_type());
        TextVeiwOrderPerson.setText(returnBodyBean.getClient_name());
        TextVeiwTweContacts.setText(returnBodyBean.getClient_tel());
        TextVeiwArtificial.setText(returnBodyBean.getLabor_consts());
        Str_Cost = returnBodyBean.getLabor_consts();
        TextViewAddress.setText(returnBodyBean.getProvince() + returnBodyBean.getCity() + returnBodyBean.getDetail_address());
        TextViewElement.setVisibility(View.GONE);
        //  TextVeiwRemarks.setText("安装时间:" + returnBodyBean.getInstall_time());
        TextVeiwTerm.setText(returnBodyBean.getInstall_time());
        if (returnBodyBean.getInstall_status() == 1) {
            btn_anzhuang.setVisibility(View.GONE);
            TextViewTotal.setText("合计:" + returnBodyBean.getTotal_price() + "元");
            btnReturn.setVisibility(View.GONE);
            btnFinish.setVisibility(View.GONE);
            feiyong.setText(returnBodyBean.getRemote_fees() + "元");
            if (returnBodyBean.getIs_check() == 1) {
                CheckCost.setChecked(true);
            } else {
                CheckCost.setChecked(false);
            }
            CheckCost.setClickable(false);
            feiyong.setClickable(false);
            ImageScene.setClickable(false);
            ImageInstall.setClickable(false);
            TextVeiwRemarks.setText(returnBodyBean.getInstall_remark() + " ");
            TextVeiwRemarks.setFocusable(false);
            Glide.with(InstallationdetailsActivity.this).load("http://" + returnBodyBean.getInstall_card())
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .into(ImageInstall);
            Glide.with(InstallationdetailsActivity.this).load("http://" + returnBodyBean.getInstall_pic())
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .into(ImageScene);
        } else if (returnBodyBean.getInstall_status() == 2) {
            btn_anzhuang.setVisibility(View.VISIBLE);
            TextViewTotal.setText("合计:" + returnBodyBean.getLabor_consts() + "元");
        }
        if (!returnBodyBean.getProduct_type().equals("净水器预约")) {
            LinearCost.setVisibility(View.GONE);
        }
        CheckCost.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    Str_Cost_He = String.valueOf(Integer.valueOf(Str_Cost) + Int_Cost + 280);
                } else {
                    Str_Cost_He = String.valueOf(Integer.valueOf(Str_Cost) + Int_Cost);
                }
                TextViewTotal.setText("合计:" + Str_Cost_He + "元");
            }
        });

        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setText("相册");
        XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setText("相机");
        cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        loadingDialog = new LoadingDialog(this);
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(ConvertUtils.REFERENCE_WIDTH).setAspectY(ConvertUtils.REFERENCE_HEIGHT);
        builder.setOutputX(ConvertUtils.REFERENCE_WIDTH).setOutputY(ConvertUtils.REFERENCE_HEIGHT);
        cropOptions = builder.create();
    }


    @OnClick({R.id.actionbar_iv_back, R.id.Image_Install, R.id.Image_Scene, R.id.btn_anzhuang, R.id.TextVeiw_OneContacts, R.id.tv_feiyong, R.id.btn_return, R.id.btn_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.btn_anzhuang:
                showNormalDialog("是否提交安装");
                break;
            case R.id.TextVeiw_OneContacts:
                Intent phoneIntent = new Intent("android.intent.action.CALL",
                        Uri.parse("tel:" + returnBodyBean.getClient_tel()));
                startActivity(phoneIntent);
                break;
            case R.id.tv_feiyong:
                getfy();//点击出现选择费用的dialog
                break;
            case R.id.btn_return:
                showNormalDialog("是否退回安装");
                break;
            case R.id.btn_finish:
                finish();
                break;
            case R.id.Image_Install:
                Str_option = "Image_Install";
                getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
                break;
            case R.id.Image_Scene:
                Str_option = "Image_Scene";
                getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
                break;
        }
    }


    void getfy() {
        // 信息列表提示框
        final String[] items = {"0", "20", "40", "60", "80", "100"};
        android.support.v7.app.AlertDialog.Builder alertBuilder = new android.support.v7.app.AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择远程费用");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int index) {
                feiyong.setText(items[index] + "");
                Int_Cost = Integer.valueOf(items[index]);
                TextViewElement.setText("元");
                TextViewElement.setVisibility(View.VISIBLE);
                if (LinearCost.getVisibility() == View.GONE) {
                    Str_Cost_He = String.valueOf(Integer.valueOf(Str_Cost) + Integer.valueOf(items[index]));
                } else {
                    if (CheckCost.isChecked()) {
                        Str_Cost_He = String.valueOf(Integer.valueOf(Str_Cost) + Integer.valueOf(items[index]) + 280);
                    }
                }
                TextViewTotal.setText("合计:" + Str_Cost_He + "元");
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }

    public void getReturn() {
        UserNetWorks.getReturn(returnBodyBean.getId() + "", TextVeiwRemarks.getText().toString(), new Subscriber<AZBean>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                loadingDialog.dismiss();
                e.printStackTrace();
            }

            @Override
            public void onNext(AZBean azBean) {
                loadingDialog.dismiss();
                if (azBean.getReturn_code().equals("FALL")) {
                    Toast.makeText(InstallationdetailsActivity.this, azBean.getReturn_msg(), Toast.LENGTH_LONG).show();
                } else if (azBean.getReturn_code().equals("SUCCESS")) {
                    Toast.makeText(InstallationdetailsActivity.this, azBean.getReturn_msg(), Toast.LENGTH_LONG).show();
                    AppCommond appCommond = new AppCommond.Builder()
                            .setOpration(AppCommond.CLOSE_ACTIVITY)
                            .setRequestcloseAcname(MainActivity.class.getSimpleName())
                            .build();
                    EventBus.getDefault().post(appCommond);
                    finish();
                }
            }
        });
    }

    public void getAZ() {
        if (LinearCost.getVisibility() == View.GONE&&ImageScene!=null) {
            isCheck = "0";
        } else {
            if (CheckCost.isChecked()) {
                isCheck = "1";

            } else {
                isCheck = "0";
            }
        }
        UserNetWorks.getAZ(returnBodyBean.getId() + "", Int_Cost + "", TextVeiwRemarks.getText().toString(), Str_Cost_He, isCheck, Str_Install, Str_Scene, new Subscriber<AZBean>() {

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                loadingDialog.dismiss();
                Log.e("信息","......");
                e.printStackTrace();
            }

            @Override
            public void onNext(AZBean azBean) {
                loadingDialog.dismiss();
                if (azBean.getReturn_code().equals("FALL")) {
                    Toast.makeText(InstallationdetailsActivity.this, azBean.getReturn_msg(), Toast.LENGTH_LONG).show();
                } else if (azBean.getReturn_code().equals("SUCCESS")) {
                    Log.e("信息",azBean.getReturn_msg());
                    Toast.makeText(InstallationdetailsActivity.this, azBean.getReturn_msg(), Toast.LENGTH_LONG).show();
                    AppCommond appCommond = new AppCommond.Builder()
                            .setOpration(AppCommond.CLOSE_ACTIVITY)
                            .setRequestcloseAcname(MainActivity.class.getSimpleName())
                            .build();
                    EventBus.getDefault().post(appCommond);
                    finish();
                }
            }
        });
    }

    private void showNormalDialog(final String str) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(InstallationdetailsActivity.this);
        normalDialog.setTitle("温馨提示");
        normalDialog.setMessage(str);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        if (str.equals("是否提交安装")) {
                            if (!Str_Install.equals("") && !Str_Scene.equals("")) {
                                if (!Str_Install.equals("shibai") && !Str_Scene.equals("shibai")) {
                                    getAZ();
                                    loadingDialog.setMessage("正在提交").show();
                                } else {
                                    Toast.makeText(InstallationdetailsActivity.this, "请上传失败请重新上传", Toast.LENGTH_LONG).show();
                                }
                            } else {
                                Toast.makeText(InstallationdetailsActivity.this, "请上传图片", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            if (!TextVeiwRemarks.getText().toString().equals("") && !TextVeiwRemarks.getText().toString().equals(null)) {
                                getReturn();
                                loadingDialog.setMessage("正在提交").show();
                            } else {
                               // loadingDialog.dismiss();
                                Toast.makeText(InstallationdetailsActivity.this, "请在备注内填写退回理由", Toast.LENGTH_LONG).show();
                            }
                        }

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }


    private void doUpload() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    //文件二进制数据
                    InputStream in = new FileInputStream(new File(pathName));
                    //普通字符串数据
                    Map<String, String> data = new HashMap<String, String>();
                    final String result = userService.userUpload(in, data);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getString("return_code").equals("SUCCESS")) {
                                    if (Str_option.equals("Image_Install")) {
                                        Str_Install = jsonObject.getString("return_body");
                                        Glide.with(InstallationdetailsActivity.this).load("http://" + jsonObject.getString("return_body"))
                                                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                                                .skipMemoryCache(true)
                                                .into(ImageInstall);
                                    } else if (Str_option.equals("Image_Scene")) {
                                        Str_Scene = jsonObject.getString("return_body");
                                        Glide.with(InstallationdetailsActivity.this).load("http://" + jsonObject.getString("return_body"))
                                                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                                                .skipMemoryCache(true)
                                                .into(ImageScene);
                                    }
                                    Toast.makeText(InstallationdetailsActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                } else if (jsonObject.getString("return_code").equals("FALL")) {
                                    if (Str_option.equals("Image_Install")) {
                                        Str_Install = "shibai";
                                    } else if (Str_option.equals("Image_Scene")) {
                                        Str_Scene = "shibai";
                                    }
                                    Toast.makeText(InstallationdetailsActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(InstallationdetailsActivity.this, "上传错误", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    void OnClick() {
        bottomDialog.show();
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(genFilePath()), cropOptions);
                bottomDialog.dismiss();
            }
        });
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
                getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(genFilePath()), cropOptions);
            }
        });
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }

    /**
     * 获取TakePhoto实例
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    /**
     * 获得一个图片地址
     */
    File genFilePath() {
        File Gallery = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    File getFilePath(String str) {
        File Gallery = new File(str);
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    @Override
    public void takeSuccess(TResult result) {
        Uri uri = getImageContentUri(InstallationdetailsActivity.this, getFilePath(result.getImage().getOriginalPath()));
        if (uri == null) {
            Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show();
        } else {
            String path = null;
            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                path = cursor.getString(columnIndex);
                cursor.close();
                Log.e("takeSuccess", uri + "");
            }
            if (path != null) {
                pathName = path;
                new AlertDialog.Builder(this).setTitle("提示")
                        .setMessage("你要上传选择的图片吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doUpload();

                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                }).create().show();
            } else {
            }
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.e("takeFail", "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.e("takeCancel", getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("onActivityResult", "" + requestCode);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

}

